#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author: Lidi
@Time  : 2019/6/10 13:35
@Desc  : AES 加解密
"""

from Crypto.Cipher import AES
import base64

aesKey = "0000000000000000"
iv = "1111111111111111"


def aes_encrypt(data):
    BS = AES.block_size
    # 补位，补够16位
    pad = (lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode('utf-8'))
    # 进行AES加密，并转为bytes类型
    aes = AES.new(aesKey.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    encrypt_data = aes.encrypt(pad(data))
    # 对AES进行base64加密，并转为str类型
    base_data = (base64.b64encode(encrypt_data)).decode("utf-8")
    return base_data, chr(BS - len(data) % BS)


def aes_decode(data, zwf):
    try:
        # 将数据转为bytes类型
        bytes_base_data = data.encode('utf-8')
        # 对数据进行base64解密
        base_data = base64.b64decode(bytes_base_data)
        aes = AES.new(aesKey.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
        # 对数据进行aes解密，并转为str类型
        encrypt_data = aes.decrypt(base_data).decode('utf-8')
        # 对占位符的删除
        retrip_data = encrypt_data.rstrip(zwf)
    except Exception as e:
        print("解密失败", e)
    else:
        return retrip_data


if __name__ == '__main__':

    data = '李迪ss'.encode('utf-8')
    ec = aes_encrypt(data)
    # 加密返回三个参数，依次为：原始密文和占位符
    print('密文:', ec)
    # 原始密文
    ec_complete = ec[0]
    # 占位符
    zwf = ec[1]
    # 注意解密一定是对原始密文解密的
    dc = aes_decode(ec_complete, zwf=zwf)
    print('明文: ', dc)


